/**
*
@author: shenxiaoxia
@date: 2020/5/6
@module: mpvue小程序接口封装
*
**/
import { getStorage } from "./storage";
// 发送请求服务器地址的配置
// let host = 'https://wx.9thsurvey.com/base'
import config from "./urlConfig";
// let host = 'https://demo.9thsurvey.com/base'
// let host = 'http://10.25.0.22:9102/base'
// let host = 'http://47.95.28.149:9102/base'
async function request(url, method, data, header = {}) {
  let _userInfo = await getStorage("userInfo");
  wx.showLoading({
    title: "加载中",
  });
  return new Promise((resolve, reject) => {
    wx.request({
      url: config.host + url,
      method: method,
      data: data,
      header: {
        "content-type": "application/json", // 默认转为json格式
        token: _userInfo.token || "",
        RN: `${_userInfo.rn}` || "",
        lang: _userInfo.lang || "zh_cn",
      },
      success: function (res) {
        if (res.statusCode === 401) {
          wx.showToast({
            icon: "none",
            title: res.data.msg,
            duration: 300,
          });
          wx.reLaunch({
            url: "/pages/firstView/main",
          });
        }
        wx.hideLoading();
        resolve(res.data);
      },
      fail: function (error) {
        wx.hideLoading();
        reject(false);
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  });
}

function get(obj) {
  return request(obj.url, "GET", obj.data);
}

function post(obj) {
  return request(obj.url, "POST", obj.data);
}

export default {
  request,
  get,
  post,
};
